package com.hhit.yb.compose_demo.views.basic

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Checkbox
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.hhit.yb.compose_demo.viewModel.Task
import com.hhit.yb.compose_demo.viewModel.TaskViewModel

@Composable
fun Tutorial2_14Screen(){
    val viewModel = viewModel<TaskViewModel>()

    val list by remember(viewModel) { viewModel.taskList }.collectAsStateWithLifecycle()
    LazyColumn {
        items(
            items = list,
            key = { it.id },
            itemContent = { task ->
                ListItem(
                    task = task,
                    onCheckedChange = { taskItem ->
                        viewModel::onCheckedChange.invoke(taskItem)
                    }
                )
            }
        )
    }
}


@Composable
private fun ListItem(task: Task, onCheckedChange: (Task) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(64.dp)
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Checkbox(
            checked = task.isCompleted,// checked,
            onCheckedChange = { onCheckedChange(task) }
        )
        Spacer(Modifier.width(8.dp))
        Text(
            text = task.title,
            style = MaterialTheme.typography.body1,
            overflow = TextOverflow.Ellipsis,
            maxLines = 1
        )
    }
}